package com.func.domain.strategy.model.entity;

import com.func.types.common.Constants;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName StrategyRuleEntity
 * @Description 策略规则实体,添加了获取分割好rule_value的方法
 * @Author: func
 * @Date 2025/2/21 21:46
 * @Version 1.0
 */

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StrategyRuleEntity {

    /** 策略ID*/
    private Long strategyId;
    /** 抽奖ID*/
    private Integer awardId;
    /** 抽奖规则类型 [1-策略类型, 2-奖品类型]*/
    private Integer ruleType;
    /** 抽奖规则类型 [rule_lock]*/
    private String ruleModel;
    /** 抽奖规则比值*/
    private String ruleValue;
    /** 抽奖规则描述*/
    private String ruleDesc;

    /**
     * 检查这条数据是不是记录了rule_weight的数据
     * 数据示例 : 4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
     * 切分RuleWeight, 切分为一个完整的权重String映射一个Int数组的形式
     * @return Map<String (4000: 102, 103, 104, 105) List<Integer> {102,103,104,105}
     */
    public Map<String, List<Integer>> getRuleWeightValue() {
        // 如果这个rule实体rule_model字段的值不是rule_weight, 说明不是用于记录weight的, 返回null
        if (!"rule_weight".equals(ruleModel)) return null;
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<String, List<Integer>> resultMap = new HashMap<>();
        for (String ruleValueGroup : ruleValueGroups) {
            if (ruleValueGroup == null || ruleValueGroup.isEmpty())
                return resultMap;

            // 分割字符串, 获取键值
            String[] parts =  ruleValueGroup.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueGroup);
            }

            // 解析值
            String key = parts[0];
            String[] valueStrings = parts[1].split(Constants.SPLIT);
            List<Integer> values = new ArrayList<>();
            for (String valueString : valueStrings) {
                values.add(Integer.parseInt(valueString));
            }
            resultMap.put(ruleValueGroup, values);
        }
        return resultMap;
    }

}
